package com.eurasia.assignment.service;

import com.eurasia.assignment.domain.Achievement;
import com.eurasia.assignment.domain.FileStorage;
import com.eurasia.assignment.infrastructure.repository.AchievementRepository;
import jakarta.annotation.PostConstruct;
import jakarta.persistence.EntityNotFoundException;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class AchievementService {

    private final AchievementRepository repository;

    private final FileStorage fileStorage;

    @Value("${file.upload-dir:./uploads}")
    private String uploadDir;

    public Achievement createAchievement(String name, String achievementType, String subtype, String specificType,
                                         String description, MultipartFile file) throws IOException {
        // 验证必填字段
        if (name == null || name.isBlank() || achievementType == null || achievementType.isBlank() ||
                subtype == null || subtype.isBlank() || specificType == null || specificType.isBlank()) {
            throw new IllegalArgumentException("Required fields (name, achievement_type, subtype, specific_type) are missing or empty");
        }

        // 创建新成就对象
        Achievement achievement = new Achievement();
        achievement.setName(name);
        achievement.setAchievementType(achievementType);
        achievement.setSubtype(subtype);
        achievement.setSpecificType(specificType);
        achievement.setDescription(description);

        // 处理文件上传
        if (file != null && !file.isEmpty()) {
            String fileName = System.currentTimeMillis() + "_" + Objects.requireNonNull(file.getOriginalFilename());
            String filePath = fileStorage.storeFile(file, fileName);
            achievement.setFilePath(filePath);
        }

        // 保存到数据库
        return repository.save(achievement);
    }

    public List<Achievement> getAllAchievements() {
        return repository.findAll();
    }

    public Achievement getAchievementById(Long id) {
        return repository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("Achievement not found with id: " + id));
    }

    public Achievement updateAchievement(Long id, String name, String achievementType, String subtype,
                                         String specificType, String description, MultipartFile file) throws IOException {
        // 获取现有成就
        Achievement achievement = getAchievementById(id);

        // 更新字段（仅当参数非空时更新）
        if (name != null && !name.isBlank()) {
            achievement.setName(name);
        }
        if (achievementType != null && !achievementType.isBlank()) {
            achievement.setAchievementType(achievementType);
        }
        if (subtype != null && !subtype.isBlank()) {
            achievement.setSubtype(subtype);
        }
        if (specificType != null && !specificType.isBlank()) {
            achievement.setSpecificType(specificType);
        }
        if (description != null) {
            achievement.setDescription(description);
        }

        // 处理文件更新
        if (file != null && !file.isEmpty()) {
            String fileName = System.currentTimeMillis() + "_" + Objects.requireNonNull(file.getOriginalFilename());
            File dest = new File(uploadDir + File.separator + fileName);
            dest.getParentFile().mkdirs();
            file.transferTo(dest);
            achievement.setFilePath("/Uploads/" + fileName);
            achievement.setFileType(file.getContentType());
        }

        // 更新时间
        achievement.setUpdatedAt(LocalDateTime.now());

        // 保存更新
        return repository.save(achievement);
    }

    public void deleteAchievement(Long id) {
        if (!repository.existsById(id)) {
            throw new EntityNotFoundException("Achievement not found with id: " + id);
        }
        repository.deleteById(id);
    }
}